<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;

/**
 * 网站管理
 *
 * @icon fa fa-circle-o
 */
class Feditionwebsite extends Backend
{
    
    /**
     * Feditionwebsite模型对象
     * @var \app\admin\model\Feditionwebsite
     */
    protected $model = null;
    protected $dataLimit = 'auth';
    protected $dataLimitField = 'admin_id';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Feditionwebsite;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("landingpageList", $this->model->LandingPageList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            $lists = $list->items();
            if($lists){
                foreach ($lists as $k=>$v){
                    $category = Db::name('fedition_category')->where('id', '=', $v['category'])->find();
                    if($category){
                        $lists[$k]['category_name'] = $category['name'];
                    }else{
                        $lists[$k]['category_name'] = '分类已删除';
                    }
                    $construction = Db::name('dns_construction')->where('id', '=', $v['platform'])->find();
                    if($construction){
                        $lists[$k]['platform_name'] = $construction['system_name'];
                    }else{
                        $lists[$k]['platform_name'] = '建站平台已删除';
                    }

                    $admin = Db::name('admin')->where('id', '=', $v['admin_id'])->find();
                    if($admin){
                        $lists[$k]['admin_name'] = $admin['nickname'];
                    }else{
                        $lists[$k]['admin_name'] = '管理员已删除';
                    }

                    $accounturl = Db::name('fedition_accounturl')->where('id', '=', $v['account_address'])->find();
                    if($accounturl){
                        $lists[$k]['account_address_name'] = $accounturl['name'];
                    }else{
                        $lists[$k]['account_address_name'] = '店铺名称已删除';
                    }

                    $domain = Db::name('dns_list')->where('id', '=', $v['domain'])->find();
                    if($domain){
                        $lists[$k]['domain_name'] = $domain['name'];
                    }else{
                        $lists[$k]['domain_name'] = '域名已删除';
                    }
                }
            }
            $result = array("total" => $list->total(), "rows" => $lists);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    //判断域名是否被使用
                    $domain_judge = $this->domain_judge($params['domain']);
                    if($domain_judge == false){
                        $this->error(__('该域名已被使用'));
                    }
                    //判断店铺是否被使用
//                    $account_address_judge = Db::name('fedition_website')->where('account_address',$params['account_address'])->find();
//                    if(!empty($account_address_judge)){
//                        $this->error(__('该店铺已被使用'));
//                    }
                    $paymentinfo = $params['paymentinfo'];
                    unset($params['paymentinfo']);
                    $params['createtime'] = time();
                    $params['updatetime'] = time();

                    //admin_id 跟店铺的amdin_id同步
                    $accounturl = Db::name('fedition_accounturl')->where('id',$params['account_address'])->find();
                    if($accounturl){
                        $params['admin_id'] = $accounturl['admin_id'];
                    }

                    $result = $this->model->allowField(true)->insertGetId($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    //如果落地页建设绑定成功则记录日志
                    if($params['landing_page'] == 1){
                        $this->add_operation_log(1,$result,3);
                    }else{
                        $this->add_operation_log(1,$result,1);
                    }
                    //绑定域名后 修改域名状态
                    $domain_usage_status = $this->domain_usage_status($params['domain'],'');
                    //如果有收款账户则填入
                    $this->paymentinfo($paymentinfo,$result);

                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $olddomain = $row['domain'];
        $oldadmin_id = $row['admin_id'];
        $oldaccount_address = $row['account_address'];
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    //判断域名是否被使用
                    if($olddomain !== $params['domain']){
                        $domain_judge = $this->domain_judge($params['domain']);
                        if($domain_judge == false){
                            $this->error(__('该域名已被使用'));
                        }
                    }
                    //判断店铺是否被使用
//                    if($oldaccount_address !== $params['account_address']){
//                        $account_address_judge = Db::name('fedition_website')->where('account_address',$params['account_address'])->find();
//                        if(!empty($account_address_judge)){
//                            $this->error(__('该店铺已被使用'));
//                        }
//                    }

                    //admin_id 跟店铺的amdin_id同步
                    if ($params['admin_id'] !== $oldadmin_id) {
                        $admin = Db::name('admin')->where('id', '=', $params['admin_id'])->find();
                        if (!empty($admin)) {
                            $accountdata['admin_id'] = $params['admin_id'];
                            Db::name('fedition_accounturl')->where('id',$params['account_address'])->update($accountdata);
                            $this->add_operation_log(8,$ids,1,$admin['nickname']);
                        }
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    //如果落地页建设绑定成功则记录日志
                    if((int)$row['landing_page'] !== (int)$params['landing_page']){
                        if($params['landing_page'] == 1){
                            $this->add_operation_log(1,$ids,3);
                        }else{
                            $this->add_operation_log(1,$ids,4);
                        }
                    }else{
                        $this->add_operation_log(1,$ids,2);
                    }
                    //绑定域名后 修改域名状态
                    $domain_usage_status = $this->domain_usage_status($params['domain'],$olddomain);
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        //域名
//        $websitedns = Db::name('fedition_websitedns')
//            ->where('website_id', '=', $row['id'])
//            ->select();
//        $domain = array();
//        foreach ($websitedns as $k=>$v){
//            $data['domain'] = $v['dns_id'];
//            $domain[] = $data;
//        }
//        if(empty($domain)){
//            $domain = '';
//        }else{
//            $domain = json_encode($domain);
//        }
//        $this->view->assign("domain", $domain);
        return $this->view->fetch();
    }

    /**
     * @return add_dnschannel
     */
//    public function add_dnschannel($params,$type)
//    {
//        $domain = json_decode($params['domain'],true);
//        if($type == 2){
//            $this->del_dnschannel($params['id']);
//        }
//        $this->handle_domain($domain,$params['id']);
//        return true;
//    }


    /**
     * @return del_dnschannel
     */
//    public function del_dnschannel($id)
//    {
//        $return = $typechannel = Db::name('fedition_websitedns')
//            ->where('website_id', '=', $id)
//            ->delete();
//        return $return;
//    }

    /**
     * @return handle_domain
     */
//    public function handle_domain($domain,$id)
//    {
//        $return = false;
//        if(!empty($domain)){
//            foreach ($domain as $k=>$v){
//                $datatype['website_id'] = $id;
//                $datatype['dns_id'] = $v['domain'];
//                $datatype['createtime'] = time();
//                $datatype['updatetime'] = time();
//                $return = Db::name('fedition_websitedns')->insert($datatype);
//            }
//        }
//        return $return;
//    }

    function arrayHandle($array){
        $temps = array();
        foreach($array as $value){
            $value = join(',',$value);//降维,也可以用implode,将一维数组转换为用逗号连接的字符串
            $temp[] = $value;
        }
        $temp = array_unique($temp);//去掉重复的字符串,也就是重复的一维数组值

        foreach( $temp as $key=>$v){
            $temps[$key]['domain'] = $v;//再将拆开的数组重新组装
        }
        return $temps;
    }
}
